import React from 'react';
import { Tree, Modal, Button, notification, message, Form, Input, Icon} from 'antd';
import FieldConverterFactory from 'components/FieldConverter';
import DBTable from './TreeDbTableView';
import './articleIndex.less';
import EditTreeNode from'./EditTreeNode.js';
import ajax from '../../../utils/ajax';
let TreeNode = Tree.TreeNode;
var _this;
var onclickType = 1;
let WrappedArticleEditForm = "";

class ArticleEditForm extends React.Component{

  constructor(props) {
    super(props);
    let form = this.props.form;
    _this.setChildTreeState({"form" : form});
  }

  render () {
    const formItems = [];
    var converter = FieldConverterFactory.getConverter(FieldConverterFactory.FormFieldConverter);
    let field = {key: "name", title: "分类名称", dataType: "varchar", max : 6, placeholder: "请输入请输入分类名称", rules:[{"message" : "请输入分类名称", "required" : true}]}
    let fieldHide = {key: "id", dataType: "hidden"};
    formItems.push(converter.convert(this, field));
    formItems.push(converter.convert(this, fieldHide));

    return (<Modal width={600}  ref='modal' title={_this.state.modelTitle} visible={_this.state.modalEditVisible} onOk={_this.handleEditModalOk}
           onCancel={_this.hideEditModal}>
      <Form onSubmit={_this.handleEditModalOk}>
        {formItems}
      </Form>
    </Modal>)
  }
}

class ChildTree extends React.Component {

  state = {
    treeName: "",
    data: [],
    requestParams:  [],
    onclickType: 1,
    modalVisible: false,
    articleTypeId: "",
    modalEditVisible: false,
    modalTitle: "",
    articleEditModal: "",
    selectedValue: "",
    editType: "",
    resetQuery: false
  };

  childTreeState = {
    form : "",
    type : "",
  }

  setChildTreeState = (obj) =>{
    this.childTreeState = obj;
  }

  getChildTreeState = () =>{
      return this.childTreeState;
  }

  constructor(props) {
    super(props);
    this.initTreeName(this.props);
    _this = this;
    WrappedArticleEditForm = Form.create()(ArticleEditForm);
  }

  refreshTree=(id)=>{
    this.initData(id);
  }

  initTreeName(props) {
    var routes;
    if (props.routes == undefined) {
      routes = props;
    }
    else {
      routes = props.routes.pop();
    }

   this.initData();
  }

  initData(id) {
    var self = this;
    const url = `/articlemanage/articleTypeList`;  // 拼接要请求的url地址
    ajax.post({
      url: url,
      success: function (res) {
        self.data = res.data.list;
        self.initTree(id);
      }
    })
  }

  editTreeNode = (id, title, type) =>{
    if (type == 1) {
      let from = this.getChildTreeState().form;
      this.setState({"modalEditVisible" : true, "modelTitle" : "编辑", editType: 1});
      if (from != "") {
        from.setFieldsValue({"id" : id, "name" : title});
      }

    } else if (type == 2) {
      this.setState({"modalVisible" : true, "articleTypeId": id, "selectedValue" : title});
    }
    onclickType = 2;
  }

  initTree(id) {
    const dataList = this.data;
    const treeNode = dataList.map((node) => {
      let editTree = <EditTreeNode treeTitle = {node.name} treeId = {node.id} editTreeNode = {this.editTreeNode}></EditTreeNode>;
      return (<TreeNode key = {node.id} title = {editTree}>
        </TreeNode>);
    });
    let firstId = (dataList instanceof Array) ? dataList[0].id : "default_id";
    let defaultId = id ? id : firstId;
    const tree =
      <Tree  defaultExpandAll onSelect = {this.onSelect} defaultSelectedKeys={[defaultId]}>
        <TreeNode title = {<EditTreeNode treeTitle = {"全部"}> </EditTreeNode>} treeId = {"default_id"}  key = {"default_id"}></TreeNode>
        {treeNode}
      </Tree>;

    this.setState({ "tree": tree ,requestParams: { catId: defaultId}});
  }

  onSelect(info) {
      console.log(info,'info');
    if (onclickType == 1 && info.length > 0) {
      let typeId = info.join("");
      console.log(typeId,'typeId');
      _this.setState({ requestParams: { catId: typeId }, resetQuery: true }, function (){
        _this.setState({resetQuery: false});
      });
    }
    onclickType = 1;
  }


  handleDeleteArtileType = () =>{

    let articleTypeId = this.state.articleTypeId;
    if (articleTypeId && articleTypeId != "") {
      _this = this;
      const url = `/articlemanage/deleteArticleType`;  // 拼接要请求的url地址
      ajax.post({
        url: url,
        params: {"id" : articleTypeId},
        success: function (res) {
          if (res.errorCode == 200) {
            message.success('修改成功');
            _this.initData(articleTypeId);
          } else if (res.errorCode == 300) {
            notification.error({
              message: '出错啦!',
              description: res.moreInfo,
              duration: 0,
            });
          }
          _this.setState({"modalVisible": false});
        }
      })
    }
  }


  handleCancel= () =>{
   this.setState({"modalVisible" : false});
  }

  hideEditModal = () =>{
    this.setState({"modalEditVisible" : false});

  }

  handleEditModalOk = (obj) =>{
    let form = this.getChildTreeState().form;
    let _this = this;
    if (form && form != "") {
      form.validateFields(function validateFieldsCallback(errorMessage, values){
        if (errorMessage == null) {

          //请求

          ajax.post({
            url: '/articlemanage/editArticleType',
            params: values,
            success: function (res) {
              if (res.errorCode == 200) {
                _this.initData();
              } else if (res.errorCode == 300) {
                notification.error({
                  message: '出错啦!',
                  description: res.moreInfo,
                  duration: 0,
                });
              }
            }
          })
          _this.setState({"modalEditVisible": false});
        }
      });
    }

  }


  createdNewType = () =>{
    let form = this.getChildTreeState().form;
    if (form != ""){
      form.resetFields();
    }
    this.setState({"modalEditVisible" : true, "modelTitle" : "添加", "editType": 2});
  }


  render() {
    return (
      <div className="articleChildTreeCon">
        <aside className="articleChildTreeAside">
          <div className="newsTitleDivClass">
            <span className="newsTitleSpanClass">新闻分类</span>
            <Button type="primary" className="newsButtonClass" onClick={this.createdNewType}>
              <Icon type="plus-circle-o" />新增分类
            </Button>
          </div>
          <div>
            {this.state.tree}
          </div>
        </aside>
        <section className="articleChildTreeSec">
          {<DBTable tableName='ArticleManage' resetQuery={this.state.resetQuery}
            refreshTree={this.refreshTree} requestParams={this.state.requestParams}/>}
          {<Modal title="删除分类" width={400} visible={this.state.modalVisible}
                 onOk={this.handleDeleteArtileType} onCancel={this.handleCancel}
                 okText="确定" cancelText="取消">
            <p>{"是否确认删除\"" + this.state.selectedValue +"\"分类？"}</p>
          </Modal>}
          {<WrappedArticleEditForm/>}
        </section>
        <div className="articleClear"></div>
      </div>
    )
  }

}

export default ChildTree;
